package org.vectrics.user;

import java.util.Collection;
import java.util.Iterator;

import org.apache.log4j.Logger;
import org.vectrics.hibernate.ThreadProperties;
import org.vectrics.provider.CoreServiceLocator;

public class UserPasswordHelper {
	private Logger log = Logger.getLogger(this.getClass());

	public void encryptAllUserPasswords() {
		PasswordEncryptor encryptor = new PasswordEncryptor();

		Collection users = CoreServiceLocator.getPersonService().findAllUsersWithNonEncryptedPasswords();
		log.info("encryptAllUserPasswords() - encrypting user passwords, found: " + users.size()
				+ " users."); 
		Iterator iter = users.iterator();
		while (iter.hasNext()) {
			User user = (User)iter.next();
			user = CoreServiceLocator.getPersonService().findUserById(user.getId());
			if (user.getPasswordEncrypted() == false) {
				if (user.getPassword() != null) {
					String encryptedPassword = encryptor.crypt(user.getPassword());
					user.setPassword(encryptedPassword);
					user.setPasswordEncrypted(true);
					CoreServiceLocator.getPersonService().updateUser(user);
					ThreadProperties.forcedCommit();
					log.info("User password encrypted, user = " + user.getUserName());
				} else {
					log.info("User does not have a password, ignoring encryption request for this user: " + user.getUserName());
				}
			} else {
				log.info("User password already encrypted, another process must have encrypted while this one was running.");
			}
		}
		ThreadProperties.forcedCommit();
	}
}
